package com.example.lesson.activitys;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lesson.R;
import com.example.lesson.lrc.SearchLRC;
import com.example.lesson.service.PlayerService;
import com.example.lesson.tools.AppConstant;
import com.example.lesson.tools.MediaUtil;
import com.example.lesson.tools.Mp3Info;

import java.util.ArrayList;
import java.util.List;

public class MusicPlaying extends Activity{

    private ImageView btnBack;
    private ImageView btnMenu;
    private SeekBar bar;
    private TextView currentTime;
    private TextView songName;
    private TextView durationTime;
    private ImageButton startPlay;
    private ImageButton previousBtn;
    private ImageButton nextBtn;
    private TextView lrc;

    private List<Mp3Info> mp3Infos;
    private Handler handler;
    private int musicId;
    private boolean isPlaying;
    private int current_time;
    private String title;
    private int sum_time;
    public MusicPlayingReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);

        findViewById();
        getDataFromMain();
        startService(new Intent(MusicPlaying.this,PlayerService.class));
        registerReceiver();
        setListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(receiver);
    }

    public void findViewById(){
        this.lrc=(TextView)findViewById(R.id.word);
        this.previousBtn=(ImageButton)findViewById(R.id.previous);
        this.nextBtn=(ImageButton)findViewById(R.id.next);
        this.btnBack=(ImageView)findViewById(R.id.backBtn);
        this.btnMenu=(ImageView)findViewById(R.id.menu);
        this.bar=(SeekBar)findViewById(R.id.seekBar);
        this.currentTime=(TextView)findViewById(R.id.currentPosition);
        this.songName=(TextView)findViewById(R.id.songName);
        this.durationTime=(TextView)findViewById(R.id.duration);
        this.startPlay=(ImageButton)findViewById(R.id.start);
        this.isPlaying=true;
        mp3Infos=MediaUtil.getMp3Infos(MusicPlaying.this);
        this.handler=new Handler();
    }

    public void registerReceiver(){
        receiver=new MusicPlayingReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction(AppConstant.MUSIC_CURRENT);
        filter.addAction(AppConstant.MUSIC_DURATION);
        filter.addAction(AppConstant.UPDATE_ACTION);
        filter.addAction(AppConstant.MUSIC_PAUSE);
        filter.addAction(AppConstant.MUSIC_PLAY);
        MusicPlaying.this.registerReceiver(receiver,filter);
    }

    public void setListener(){
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MusicPlaying.this,MainActivity.class);
                intent.putExtra("title",title);
                startActivity(intent);
            }
        });
        startPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPlaying) {

                    startPlay.setBackgroundResource(R.drawable.start);
                    Toast.makeText(MusicPlaying.this, "暂停", Toast.LENGTH_SHORT).show();
                    Intent intent=new Intent();
                    intent.putExtra("MSG",AppConstant.PAUSE_MSG);
                    intent.setClass(MusicPlaying.this, PlayerService.class);
                    startService(intent);

                }else{

                    startPlay.setBackgroundResource(R.drawable.stop);
                    Toast.makeText(MusicPlaying.this, "播放", Toast.LENGTH_SHORT).show();
                    Intent intent=new Intent();
                    intent.putExtra("MSG",AppConstant.CONTINUE_MSG);
                    intent.setClass(MusicPlaying.this,PlayerService.class);
                    startService(intent);

                }
            }
        });
        previousBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(musicId==0){
                    Toast.makeText(MusicPlaying.this,"已经是第一首了！",Toast.LENGTH_SHORT).show();
                }else{
                    startPlay.setBackgroundResource(R.drawable.stop);
                    Intent intent=new Intent();
                    intent.putExtra("musicId",musicId-1);
                    intent.putExtra("MSG",AppConstant.PRIVIOUS_MSG);
                    intent.setClass(MusicPlaying.this,PlayerService.class);
                    startService(intent);

                }

            }
        });
        nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(musicId==mp3Infos.size()-1){
                    Toast.makeText(MusicPlaying.this,"已经是最后一首了！",Toast.LENGTH_SHORT).show();
                }else{
                    startPlay.setBackgroundResource(R.drawable.stop);
                    Intent intent=new Intent();
                    intent.putExtra("musicId",musicId+1);
                    intent.putExtra("MSG",AppConstant.NEXT_MSG);
                    intent.setClass(MusicPlaying.this,PlayerService.class);
                    startService(intent);
                }
            }
        });
        bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // fromUser判断是用户改变的滑块的值
                if (fromUser == true) {
                    Intent intent = new Intent();
                    intent.putExtra("musicId", musicId);
                    intent.putExtra("progress",progress);
                    intent.putExtra("MSG", AppConstant.PROGRESS_CHANGE);
                    intent.setClass(MusicPlaying.this, PlayerService.class);
                    startService(intent);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }


        });
        btnMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openOptionsMenu();
            }
        });

    }

    public class MusicPlayingReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action=intent.getAction();
            if(action.equals(AppConstant.MUSIC_CURRENT)){
                current_time=intent.getIntExtra("currentPosition",-1);
                bar.setProgress(current_time);
                currentTime.setText(MediaUtil.formatTime(current_time));
            }else if(action.equals(AppConstant.MUSIC_DURATION)){
                sum_time=intent.getIntExtra("duration",-1);
                bar.setMax(sum_time);
                durationTime.setText(MediaUtil.formatTime(sum_time));
            }else if(action.equals(AppConstant.UPDATE_ACTION)){
                musicId=intent.getIntExtra("musicId",-1);
                if(musicId>=0&&musicId<mp3Infos.size()){
                    title=mp3Infos.get(musicId).getTitle();
                    songName.setText(title);
                }
            }else if(action.equals(AppConstant.MUSIC_PAUSE)){
                isPlaying=intent.getBooleanExtra("isPlaying",true);
            }else if(action.equals(AppConstant.MUSIC_PLAY)){
                isPlaying=true;
                startPlay.setBackgroundResource(R.drawable.stop);
                musicId=intent.getIntExtra("musicId",-1);
                title=mp3Infos.get(musicId).getTitle();
                songName.setText(title);
            }
        }
    }

    public void getDataFromMain(){
        Intent intent=getIntent();
        musicId=intent.getIntExtra("musicId",-1);
        title=mp3Infos.get(musicId).getTitle();
        songName.setText(title);
        sum_time=intent.getIntExtra("duration",-1);
        isPlaying=intent.getBooleanExtra("isPlaying",true);
        durationTime.setText(MediaUtil.formatTime(sum_time));
        bar.setMax(sum_time);
        //歌词功能：革命尚未成功，我还须努力！！！
//        Looper.prepare();
//        getWords();
//        Looper.loop();

    }

    private void getWords() {

        SearchLRC search = new SearchLRC(title, mp3Infos.get(musicId).getArtist());
        ArrayList result = search.fetchLyric();

        if(result == null){
            Toast.makeText(MusicPlaying.this, "Can't seach song word of "+title+"", Toast.LENGTH_LONG);
            return;
        }
        String word = "";
        if (result.size() > 0) {
            for (int i = 0; i < result.size(); i++) {
                word += result.get(i);
                word += "\n";
                Log.d("CHENGJR1", "word1 = " + word);
            }
        }
        lrc.setText(word);


    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        SubMenu share=menu.addSubMenu("分享");
        share.add(0,1,1,"微信分享").setIcon(R.drawable.weixin);
        share.add(0,2,2,"短信分享").setIcon(R.drawable.duanxin);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch(item.getItemId()){

            case 1:
//                Toast.makeText(this,"微信分享",Toast.LENGTH_SHORT).show();
                String weixinPackage="com.tencent.mm";
                if(checkBrowser(weixinPackage)){

                    Intent mIntent = new Intent( );
                    ComponentName comp = new ComponentName(weixinPackage, "com.tencent.mm.ui.LauncherUI");
                    mIntent.setComponent(comp);
                    mIntent.setAction("android.intent.action.VIEW");
                    startActivity(mIntent);
                }else {
                    Toast.makeText(this,"亲，你还没有安装QQ微信，赶紧下一个去吧！",Toast.LENGTH_SHORT).show();
                }
                break;
            case 2:
//                Toast.makeText(this,"短信分享",Toast.LENGTH_SHORT).show();
                Intent it = new Intent(Intent.ACTION_VIEW);
                it.putExtra("sms_body", "我正在听“" + title + "”");
                it.setType("vnd.android-dir/mms-sms");
                startActivity(it);
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    //判断是否存在应用程序
    public boolean checkBrowser(String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = getPackageManager().getApplicationInfo(
                    packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }
}
